package mobmap.conf;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
/**
 * Retidado de: http://wiki.forum.nokia.com/index.php/Como_desenvolver_um_jogo_em_Java_ME_-_Parte_5
 * @author NOKIA
 */
public class Settings {
  public Hashtable values;
  
  public Settings(String file) {    
    values = new Hashtable(10);    
    read(file);
  }
  
  public String getSetting(String key){
    return (String)(values.get(key));
  }
  
  /**
   * Opens the file and reaas all the settings to the hashtable
   * @param file, the name of the file to read
   */
  public void read(String file){
    // open file
    InputStream is = this.getClass().getResourceAsStream(file);
    InputStreamReader isr = new InputStreamReader(is);
    // create a buffer to store lines
    StringBuffer lineBuffer = new StringBuffer();
    int c;
    try {
      c = isr.read();      
      while(c != -1){        
        lineBuffer.append((char)c);
        c = isr.read();
        // checks for end of line character
        if ( c == 10 || c==-1){
          // cleans extra spaces or end of lines chars
          String line = lineBuffer.toString().trim();
          // splits the string using the = character
          int pos = line.indexOf("=");
          if (pos != -1){
            // adds a new setting
            String key = line.substring(0,pos);            
            String value = line.substring(pos+1);     
            values.put(key, value);            
          }
          // clean buffer
          lineBuffer.setLength(0);
        }
      }
    } catch (IOException e) {      
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {        
        e.printStackTrace();
      }
    }    
  }    
}